import io
from django.http import FileResponse, JsonResponse, Http404
from djangomodel import settings
from djangomodel.err import *
from djangomodel.my_rest_framework import MyGenericAPIView
from .models import FileModel,FolderModel
from djangomodel.storage import LocalStorage
from djangomodel.tools import get_file_cls

# 文件管理
class FileView(MyGenericAPIView):
    http_method_names = ['get', 'post',"delete"]
    models = FileModel
    storage = LocalStorage()

    # 上传文件
    def post(self, request, *args, **kwargs):
        files = request.FILES
        for _, file in files.items():
            if file.size > settings.MAX_UPLOAD_SIZE:
                return JsonResponse({'status':400,"msg":f"{file.name}文件大小超出范围!"})
            cls = get_file_cls(file.name)
            file_obj = FileModel.objects.create(name=file.name,size=file.size,cls=cls)
            try:
                self.storage.save(file_obj.uuid.__str__(), file.file.read())
            except Exception as e:
                file_obj.delete()
                raise e
        return JsonResponse({'status':200,"msg":"文件上传成功!"})

    # 下载
    def get(self, request, *args, **kwargs):
        uuid = request.GET.get('uuid',None)
        if uuid is not None:
            try:
                file = FileModel.objects.get(uuid=uuid)
            except FileModel.DoesNotExist:
                return JsonResponse({"status": 200, "msg": "文件不存在!"})
            file_data = self.storage.read(uuid)
            data = io.BytesIO(file_data)
            return FileResponse(streaming_content=data,filename=file.name)
        else:
            return JsonResponse({"status":400,"msg":"未传入文件ID参数!"})

    # 删除
    def delete(self,request,*args,**kwargs):
        uuid = request.GET.get('uuid',None)
        if uuid is not None:
            try:
                file = FileModel.objects.get(uuid=uuid)
            except FileModel.DoesNotExist:
                return JsonResponse({"status": 200, "msg": "文件不存在!"})
            self.storage.delete(uuid)
            file.delete()
            return JsonResponse({"status":200,"msg":"文件删除成功!"})
        else:
            return JsonResponse({"status": 400, "msg": "未传入文件ID参数!"})

